package com.usf.jprovider.schema.model.jmodel.item.field;

import javax.xml.bind.annotation.XmlElement;

import com.usf.jprovider.constants.Constants;
import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.builder.SQLBuilder;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.schema.condition.AbstractCondition;
import com.usf.jprovider.schema.condition.EmptyCondition;
import com.usf.jprovider.schema.model.jmodel.item.AbstractItem;

public final class ConditionFields extends AbstractField {
	
	@XmlElement protected AbstractCondition condition;
	@XmlElement(name="field") 
	protected AbstractField[] fields;

	public ConditionFields() {
		super();
		condition = new EmptyCondition();
		fields = new AbstractField[]{};
	}
	public AbstractCondition getCondition() {
		return condition;
	}
	public AbstractField[] getFields() {
		return fields;
	}
	
	@Override
	public void create(Environment env, JObjectNode parent) throws Exception {
		if(!check_simuleChild(env, parent))return;
		_create(env, parent);
	}
	@Override
	protected void _create(Environment env, JObjectNode node) throws Exception {
		for(AbstractItem item : fields)
			item.create(env, node);
	}
	@Override
	public boolean check(Environment env, JObjectNode parent) throws Exception {
		if(!check_simuleChild(env, parent)) return true;
		return _check(env, parent);
	}
	@Override
	protected boolean _check(Environment env, JObjectNode node) throws Exception {
		for(AbstractItem item : fields){
			if(!item.check(env, node)) return false;
		}
		return true;
	}
	@Override
	public void persist(Environment env, JObjectNode parent, SQLBuilder builder) throws Exception {
		if(!check_simuleChild(env, parent)) return;
		_persist(env, parent, builder);
	}
	@Override
	protected void _persist(Environment env, JObjectNode node, SQLBuilder builder) throws Exception {
		for(AbstractItem item : fields)
			item.persist(env, node, builder);
	}
	
	private boolean check_simuleChild(Environment env, JObjectNode node) throws Exception {
		JObjectNode tmp = node.create(Constants.TAG_TEMP_NAME);
		node.addChild(tmp);
		boolean value = condition.check(env, tmp);
		node.removeChild(tmp);
		return value;
	}

}
